import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(config => {
  // config当前请求的配置
  // 如果有token就带上(把token设置到请求头中)
  const token = store.state.user.token
  console.log('token', token)
  if (token) {
    config.headers.Authorization = `Bearer  ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  }, (err) => {
    console.log(err.response)
    if (err.response?.status === 401) {
      store.commit('user/delToken')
      // 登录跳转
      // router.push('/login')
      Message.error('登录过期，请重新登录')
    } else {
      Message.error(err?.response?.data?.message || '系统出错')
    }
    return Promise.reject(err)
  })
export default request

